package com.heima.apuser.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.apuser.mapper.ApUserMapper;
import com.heima.apuser.service.ApUserService;


import com.heima.model.common.dtos.LoginDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.pojo.ApUser;

import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;


import java.util.HashMap;
import java.util.Map;

@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {


    @Override
    public ResponseResult login(LoginDto dto) {


        /*
         * 格式正确去数据库查找  如果没有还是返回错误
         *
         * 如果有就取密码
         * password加盐加密和取出来的对比
         *
         *
         *
         * */
        //游客访问
        if (StringUtils.isBlank(dto.getPassword()) && StringUtils.isBlank(dto.getPhone())) {
            Map<String, Object> map = new HashMap<>();
            map.put("token", AppJwtUtil.getToken(0L));
            return ResponseResult.okResult(map);
        } else {
            String dtoPhone = dto.getPhone();

            //根据phone选取得到user
            LambdaQueryWrapper<ApUser> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ApUser::getPhone, dtoPhone);
            ApUser apUser = getOne(queryWrapper);
            //取出为空  返回没有
            if (apUser == null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_NOT_EXIST);
            }
            //不为空 判断密码
            String salt = apUser.getSalt();
            String dtoPassword = dto.getPassword();
            String md5Password = DigestUtils.md5DigestAsHex((dtoPassword + salt).getBytes());
            if (!md5Password.equals(apUser.getPassword())) {
                return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_NOT_EXIST);
            }
            Map<String, Object> map = new HashMap<>();
            map.put("token", AppJwtUtil.getToken(apUser.getId().longValue()));
            apUser.setSalt("");
            apUser.setPassword("");
            map.put("user",apUser);
            return ResponseResult.okResult(map);
        }
    }
}
